from django.conf                 import settings
from django.core.management.base import BaseCommand,CommandError
from sitepal.sitebase.management import setup
from sitepal.sitebase.util       import iterappmodules

if settings.DEBUG:
    import sys,traceback

class Command(BaseCommand):
    def handle(self,*labels,**options):
        for app,mod in iterappmodules(submodule='siteapp.setup'):
            pass
        if not labels:
            for name,handler in setup.registered_handlers.iteritems():
                self.handle_setup(name,handler,**options)
        elif name in setup.registered_setups:
            self.handle_setup(name,setup.registered_setups[name],**options)

    def handle_setup(self,name,handler,**options):
        try:
            print "setting up {0} ...".format(name)
            handler.syncdb()
        except setup.SetupError,e:
            if settings.DEBUG:
                exc_type,exc_value,exc_traceback = sys.exc_info()
                traceback.print_exception(exc_type,exc_value,exc_traceback,limit=2,file=sys.stdout)
            raise CommandError(str(e))

